package com.example.androidsocketclient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.StringTokenizer;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.MultiAutoCompleteTextView.Tokenizer;
import android.widget.TextView;


public class MainActivity extends Activity {

	Button login_btn;
	
	EditText login_id_edt;
	TextView login_id_txt;
	EditText login_ip;//ip_address
	EditText login_port;//prot
	TextView log_main;//로그 
	
	ListView user_list; //user_list
	TextView user_cnt_txt; //접속자 체크 
	Handler handler;
	
	String id;
	
	ArrayList<UserVO> userArr; //로그인 된 유저 리스트 
	Context context;
	
	
	boolean running = true;//thread key
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        handler = new Handler();
        userArr = new ArrayList<UserVO>();
        context = MainActivity.this;
        settingComponent();
    }
    
    private void settingComponent()
    {
    	login_btn = (Button)findViewById(R.id.login_btn);
    	login_id_edt = (EditText)findViewById(R.id.login_id_edt);
    	login_id_txt = (TextView)findViewById(R.id.login_id_txt);
    	login_ip = (EditText)findViewById(R.id.login_ip);
    	login_port = (EditText)findViewById(R.id.login_port);
    	user_list = (ListView)findViewById(R.id.user_list);
    	log_main = (TextView)findViewById(R.id.log_main);
    	user_cnt_txt = (TextView)findViewById(R.id.user_cnt_txt); 
    			
    	
    	setClickEventListner();
    }
    
    private void setClickEventListner()
    {
    	login_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Global.instance = new ChatThread();
				Global.instance.start();
				
			}
		});
    }
    
    
    
    class ChatThread extends Thread {
    	
		Socket socket;
		
		byte[] buffer = new byte[1024];
		
		
		public void run() {
			connect();
			
			while(running) {
				try {
					if (Global.instream != null) {
						int inputCount = Global.instream.read(buffer, 0, 1024);
						println("input count : " + inputCount);
						
						String inputData = new String(buffer, 0, inputCount, "UTF-8");
						println("input data : " + inputData);
						
						StringTokenizer tokenizer = new StringTokenizer(inputData, "|");
						String token1 =tokenizer.nextToken(); 
						String token2 =tokenizer.nextToken(); 
						String token3 =tokenizer.nextToken(); 
						String token4 =tokenizer.nextToken();
						
						if(token1.equals(Global.SERVICE_LOGIN))
						{
							UserVO uvo = new UserVO(token2);
							userArr.add(uvo);
							addListView_Item();
						}else if(token1.equals(Global.SERVICE_SEND)){
							Message message = Global.chatHandler.obtainMessage(); //핸들러객체로부터 message 얻어오기 
							message.what = Global.SEND_MESSAGE;
							message.obj = inputData;
							Global.chatHandler.sendMessage(message);
						}
						
					}
				} catch(Exception ex) {
					ex.printStackTrace();
					running = false;
					finish();
				}
			}
		}
		
		private void connect() {

			String host = "";
			int port = 0;
			
			try {
				host = login_ip.getText().toString().trim();
				String portStr = login_port.getText().toString().trim();
				port = Integer.parseInt(portStr);
				id = login_id_edt.getText().toString().trim();
				
				socket = new Socket(host, port);
				println("서버 접속 host & port : " + host + ", " + port);

				Global.instream = new DataInputStream(socket.getInputStream());
				Global.outstream = new DataOutputStream(socket.getOutputStream());
				
				// LOGIN
				String outputData = "LOGIN|" + id + "|" + id + "|" + id;
				byte[] outputBytes = outputData.getBytes("UTF-8");
				
				Global.outstream.write(outputBytes, 0, outputBytes.length);
				Global.outstream.flush();
				println("서버로 보낸 내용 : " + outputData);
				
				
			} catch (Exception e) {
				e.printStackTrace();
				running = false;
			}
			
		}
		
		public void requestSend(String sId, String rId,String sendData) {
			// SEND
			String senderId = sId;
			String receiverId = rId;
			String data = sendData;
			String outputData = "SEND|" + senderId + "|" + receiverId + "|" + data;
			
			write(Global.outstream, outputData);
		}
		
		private void write(DataOutputStream stream, String data) {
			try {
				byte[] outputBytes = data.getBytes("UTF-8");
				
				stream.write(outputBytes, 0, outputBytes.length);
				stream.flush();
				println("보낸 메시지 내용 : " + data);
			} catch(Exception ex) {
				ex.printStackTrace();
			}
		}
		
	}
	
	private void println(String msg) {
		final String curMsg = msg;
		handler.post(new Runnable() {
			public void run() {
				log_main.append(curMsg + "\n");
			}
		});
	}
	private void addListView_Item() {
		handler.post(new Runnable() {
			public void run() {
				String login_id = login_id_edt.getText().toString();
				login_id_txt.setText(login_id);
				login_id_edt.setVisibility(View.INVISIBLE);
				login_id_txt.setVisibility(View.VISIBLE);
				user_cnt_txt.setText("현재접속자 : "+userArr.size() + " 명");
				UserListAdapter adapter = new UserListAdapter(context, R.layout.user_ilist_item, userArr, login_id);
				user_list.setAdapter(adapter);
			}
		});
	}
    


}
